package com.twotiger.and.activity.current;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import app.twotiger.p2p.R;
import app.twotiger.p2p.R.color;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.twotiger.and.Constants;
import com.twotiger.and.TwoTigerApp;
import com.twotiger.and.activity.WebViewPage;
import com.twotiger.and.activity.base.AbastractListItem;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.activity.base.BaseListItem;
import com.twotiger.and.activity.base.SubTitle;
import com.twotiger.and.adapter.BaseListAdapter;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.BroswerUrl;
import com.twotiger.and.bean.ConstantDataUnit;
import com.twotiger.and.bean.CurrentAccount;
import com.twotiger.and.bean.CurrentProject;
import com.twotiger.and.util.ArithUtils;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.TimeUtils;
import com.twotiger.and.util.PromptManager.ReChargeClickListener;
import com.umeng.analytics.MobclickAgent;
import com.view.pulltorefresh.PullToRefreshBase;
import com.view.pulltorefresh.PullToRefreshScrollView;

/**
 * 项目详情
 * @Description: 
 * intent需要携带 PROJECT_Id or PROJECT_DETAIL
 * @Author douxy
 * @Date 2015年8月12日 下午2:43:22
 */
public class CurrentHost extends BaseActivity implements OnClickListener {

    private static final int GETCURRENTPROJECTSUCCES = 0;
    private static final int GETCURRENTPROJECTFAIL = 1;
    private static final int OPENAUTOCURRENTPROJECTSUCCES = 2;
    private static final int OPENAUTOCURRENTPROJECTFAIL = 3;
    public final static int GETCURRENTPROJECTXACOUNTSUCCES = 4;
    public final static int GETCURRENTPROJECTXACOUNTFAIL = 5;

    public final static String TIGER_HOST = "TIGER_HOST";

    private static HashMap<String, String> params;
    private SubTitle subTitle;

    private ListView baseList;
    private BaseListAdapter baseListaAdapter;
    private CurrentAccount mCurrentAccount;
    private TextView tv_profit_yestoday, tv_current_amount, tv_profit_day, tv_profit_all;
    private Button btn_out, btn_in;
    private ImageView iv_compound;

    /**活期转入流程各个页面启动标志*/
    public static final int CURRENTREQUEST = 20;
    /**活期转入流程各个页面关闭的标示(成功)*/
    public static final int CURRENTRESULTCLOSE_SUC = 21;
    /**活期转入流程各个页面关闭的标示(失败)*/
    public static final int CURRENTRESULTCLOSE_FAI = 22;
    private PullToRefreshScrollView current_host_sc;
    private TextView tv_invest_amount;
    private RelativeLayout rl_active;
    private TextView tv_active_content;

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.current_host_layout, null);
        return view;
    }

    @Override
    protected void findViewById(View view) {
        subTitle = new SubTitle(view) {
            @Override
            protected void clickTitle(View v) {
            }

            @Override
            protected void clickRightBtn(View v) {
            }

            @Override
            protected void cickLeftBtn(View v) {
                onBackPress();
            }
        };
        subTitle.setTitle("老虎活期");
        subTitle.hideBtns();
        subTitle.hideBottomLine();
        tintManager.setTintResource(R.drawable.bg_account_statusbar);
        subTitle.setBgResource(R.drawable.bg_account_title);
        subTitle.setColor(getResources().getColor(color.white));
        subTitle.title_left_bt.setVisibility(View.VISIBLE);
        subTitle.title_left_bt.setImageResource(R.drawable.back_w);
        subTitle.title_right_bt.setImageResource(R.drawable.current_help);
        subTitle.title_right_bt.setVisibility(View.VISIBLE);

        baseList = (ListView) view.findViewById(R.id.base_list);
        baseList.setFocusable(false);
        tv_profit_yestoday = (TextView) view.findViewById(R.id.tv_profit_yestoday);
        tv_current_amount = (TextView) view.findViewById(R.id.tv_current_amount);
        tv_profit_day = (TextView) view.findViewById(R.id.tv_profit_day);
        tv_profit_all = (TextView) view.findViewById(R.id.tv_profit_all);
        btn_out = (Button) view.findViewById(R.id.btn_out);
        btn_in = (Button) view.findViewById(R.id.btn_in);
        current_host_sc = (PullToRefreshScrollView) view.findViewById(R.id.current_host_sc);
        iv_compound = (ImageView) view.findViewById(R.id.iv_compound);
        tv_invest_amount = (TextView) view.findViewById(R.id.tv_invest_amount);
        rl_active = (RelativeLayout) view.findViewById(R.id.rl_active);
        tv_active_content = (TextView) view.findViewById(R.id.tv_active_content);

        View fl_inner = current_host_sc.findViewById(R.id.fl_inner);
        fl_inner.setBackgroundColor(getResources().getColor(app.twotiger.p2p.R.color.bg_1));

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.rl_active: //活期活动入口
            if(mCurrentAccount == null){
                return;
            }
            MobclickAgent.onEvent(mContext, Constants.UMENG_EVENT_CURRENT_HOSTCLICK);
            Intent in1 = new Intent(CurrentHost.this, WebViewPage.class);
            in1.putExtra("title", "活期刮刮卡");
            in1.putExtra("url", mCurrentAccount.getActivityUrl());
            in1.putExtra("BACK_MODE", WebViewPage.BACK_DIRECT);
            startNewActivity(in1, R.anim.push_left_in, R.anim.push_left_out, false);
            
            break;
        case R.id.iv_compound:
            if(mCurrentAccount == null){
                return;
            }
            PromptManager.showCurrentAlert(
                CurrentHost.this,
                "复合年利率",
                "复合年利率是指收益复投后的年化收益，老虎活期采用收益复投的方式，所以复合年利率会高于基础年利率。\n基础年利率："
                        + ArithUtils.coverMoney(mCurrentAccount.getYield()+"") + "%\n基础万元日收益：￥"
                        + ArithUtils.coverMoneyFour(mCurrentAccount.getInterestUnits()+""));
            break;
        case R.id.sub_title_right_bt:
            ConstantDataUnit hqjs = getConstantDataByKey(Constants.dz_hqjs);
            if(hqjs != null){
                Intent int1 = new Intent();
                int1.setClass(getContext(), WebViewPage.class).putExtra("title", hqjs.getName())
                .putExtra("url", hqjs.getVal()).putExtra("TIGER_HOST", TIGER_HOST);
                startNewActivity(int1, R.anim.push_left_in, R.anim.push_left_out, false);
            }
            break;
        case R.id.btn_in:
            if (TwoTigerApp.getInstance().getUser().hasOpenProjectXAct) {
                getCurrentProject();
            } else {
                PromptManager.showCurrentAlertHasBtn(CurrentHost.this, "",
                    "参与老虎活期，需要您授权开通账户自动投资功能。\n自动投资将仅用于活期每日复投，不会影响到其他资金。", "立即开通", false, new ReChargeClickListener() {

                        @Override
                        public void onClickConfirm() {
                            openAutoCurrentProject();
                        }

                        @Override
                        public void onClickCancel() {

                        }
                    });
            }
            break;
        case R.id.btn_out:
            if (TwoTigerApp.getInstance().getUser().hasOpenProjectXAct) {
                Intent intent2 = new Intent(CurrentHost.this, CurrentInputAmountOutPage.class);
                startNewActivity(intent2, R.anim.slide_in_from_bottom, R.anim.silent_anim, false);
            } else {
                PromptManager.showCurrentAlertHasBtn(CurrentHost.this, "",
                    "参与老虎活期，需要您授权开通账户自动投资功能。\n自动投资将仅用于活期每日复投，不会影响到其他资金。", "立即开通", false, new ReChargeClickListener() {

                        @Override
                        public void onClickConfirm() {
                            openAutoCurrentProject();
                        }

                        @Override
                        public void onClickCancel() {

                        }
                    });
            }
            break;
        default:
            break;
        }
    }

    private void getCurrentProject() {
        params.clear();
        params.put("token", getToken());
        getDate(params, Constants.PROJECTXQUERY, handler, GETCURRENTPROJECTSUCCES,
            GETCURRENTPROJECTFAIL, true, false, false);
    }

    private void openAutoCurrentProject() {
        params.clear();
        params.put("token", getToken());
        getDate(params, Constants.PROJECTXOPEN, handler, OPENAUTOCURRENTPROJECTSUCCES,
            OPENAUTOCURRENTPROJECTFAIL, true, false, false);
    }

    @Override
    protected void setListener() {

        handler = new BaseHandler(this) {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case OPENAUTOCURRENTPROJECTSUCCES:
                    Basebean result = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result.isOk()) {
                        BroswerUrl url = JSONObject.parseObject(result.data, BroswerUrl.class);
                        Intent intent = new Intent(CurrentHost.this, WebViewPage.class);
                        intent.putExtra("title", "账户自动投资");
                        intent.putExtra("url", url.getUrl());
                        intent.putExtra("SHOWPASSWORD", "showPassword");
                        intent.putExtra("BUSINESS_TYPE", WebViewPage.TYPE_OPEN_AUTO_PROJECT);
                        startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
                    } else {
                        showToast(result.codeDesc);
                    }
                    break;
                case OPENAUTOCURRENTPROJECTFAIL:
                    showToast("网络异常");
                    break;
                case GETCURRENTPROJECTSUCCES:
                    Basebean result_g = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_g.isOk()) {
                        CurrentProject mCurrentProject = JSONObject.parseObject(result_g.data,
                            CurrentProject.class);
                        Intent intent2 = new Intent(CurrentHost.this, CurrentInputAmountPage.class);
                        intent2.putExtra("CURRENTPROJECT", mCurrentProject);
                        startNewActivityforresult(intent2, R.anim.slide_in_from_bottom,
                            R.anim.silent_anim, CURRENTREQUEST);
                    } else {
                        showToast(result_g.codeDesc);
                    }
                    break;
                case GETCURRENTPROJECTFAIL:
                    showToast("网络异常");
                    break;
                case GETCURRENTPROJECTXACOUNTSUCCES:
                    Basebean result_c = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_c.isOk()) {
                        current_host_sc.getLoadingLayoutProxy().setLastUpdatedLabel(
                            "最后更新：今天 " + TimeUtils.getFormatDate(" HH:mm"));
                        mCurrentAccount = JSON.parseObject(result_c.data, CurrentAccount.class);
                        initData();
                    } else {
                        showToast(result_c.codeDesc);
                    }
                    current_host_sc.onRefreshComplete();
                    break;
                case GETCURRENTPROJECTXACOUNTFAIL:
                    showToast("网络异常");
                    current_host_sc.onRefreshComplete();
                    break;
                default:
                    break;
                }

                super.handleMessage(msg);
            }
        };
        current_host_sc
            .setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
                @Override
                public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                    getCurrentProAcc();
                }

                @Override
                public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {

                }
            });
        btn_out.setOnClickListener(this);
        btn_in.setOnClickListener(this);
        subTitle.title_right_bt.setOnClickListener(this);
        iv_compound.setOnClickListener(this);
        rl_active.setOnClickListener(this);
    }

    @Override
    protected void onActivityResult(int requestcode, int resultcode, Intent intent) {
        super.onActivityResult(requestcode, resultcode, intent);
        if (requestcode == CURRENTREQUEST) {
            if (resultcode == CURRENTRESULTCLOSE_SUC) {

            }
        }
    }

    @Override
    protected void processLogic() {
        params = getParm();

        ArrayList<AbastractListItem> datas = new ArrayList<AbastractListItem>();
        datas.add(new BaseListItem("资产匹配详情", true, new ItemClick(CurrentAssertMatchPage.class),
            R.color.gray_1));
        datas.add(new BaseListItem("操作记录", false, new ItemClick(CurrentOperationRecordPage.class),
            R.color.gray_1));
        datas.add(new BaseListItem("收益记录", false, new ItemClick(CurrentProfitRecordPage.class),
            R.color.gray_1));
        baseListaAdapter = new BaseListAdapter(CurrentHost.this, datas);
        baseList.setAdapter(baseListaAdapter);

        mCurrentAccount = (CurrentAccount) getIntent().getSerializableExtra("CURRENTACCOUNT");
        if (mCurrentAccount == null) {
            getCurrentProAcc();
        } else {
            initData();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        getCurrentProAcc();
    }

    private void getCurrentProAcc() {
        params.clear();
        params.put("token", getToken());
        getDate(params, Constants.ASSETXQUERY, handler,
            GETCURRENTPROJECTXACOUNTSUCCES, GETCURRENTPROJECTXACOUNTFAIL, false, true, false);
    }

    private void initData() {
        current_host_sc.getLoadingLayoutProxy().setLastUpdatedLabel(
            "最后更新：今天 " + TimeUtils.getFormatDate(" HH:mm"));
        tv_profit_yestoday.setText(ArithUtils.coverMoneyComma(mCurrentAccount
            .getYesterdayInterest() + ""));
        tv_current_amount.setText(ArithUtils.coverMoneyComma(mCurrentAccount.getAmount() + ""));
        tv_profit_day.setText(ArithUtils.coverMoneyFour(mCurrentAccount.getInterestUnits() + ""));
        tv_profit_all.setText(ArithUtils.coverMoneyComma(mCurrentAccount.getCompoundYield() + "") + "");
        tv_invest_amount.setText(ArithUtils.coverMoneyComma(mCurrentAccount.getTotalInterest() + "") + "");
        if ("1".equals(mCurrentAccount.getActivityMark())) {
            rl_active.setVisibility(View.VISIBLE);
            tv_active_content.setText(mCurrentAccount.getActivityName());
        } else {
            rl_active.setVisibility(View.GONE);
        }
    }

    class ItemClick implements BaseListItem.OnClick {
        private Class<? extends Activity> clazz;

        public ItemClick(Class<? extends Activity> clazz) {
            this.clazz = clazz;
        }

        @Override
        public void onClick() {
//            if (!TwoTigerApp.getInstance().getUser().hasOpenProjectXAct) {
//                PromptManager.showCurrentAlertHasBtn(CurrentHost.this, "",
//                    "参与老虎活期，需要您授权开通账户自动投资功能。\n自动投资将仅用于活期每日复投，不会影响到其他资金。", "立即开通", false, new ReChargeClickListener() {
//
//                        @Override
//                        public void onClickConfirm() {
//                            openAutoCurrentProject();
//                        }
//
//                        @Override
//                        public void onClickCancel() {
//
//                        }
//                    });
//                return;
//            }
            Intent intent = new Intent(CurrentHost.this, clazz);
            startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
        }

    }

    @Override
    protected void onBackPress() {
        finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

}
